package com.cgw.common.service.conf;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * BigDecimal
 * 序列化格式
 *
 * @author grl
 * @date 2024/8/7
 */
public class BigDecimalSerialize extends JsonSerializer<BigDecimal> {

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
        } else {
            BigDecimal formatNum = value.setScale(2, RoundingMode.HALF_EVEN);
            String formattedValue = DECIMAL_FORMAT.format(formatNum);
            gen.writeString(formattedValue);
        }
    }
}
